import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import { fetchValidation } from '@/utils';
import {
  queryList,
  queryPartner,
  allowAudit,
  refuseAudit,
  relieveAudit,
  arrearsAvailable,
} from './service';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    fetchPartner: Effect;
    allow: Effect;
    refuse: Effect;
    relieve: Effect;
    arrears: Effect;
  };
  reducers: {
    save: Reducer;
    savePartner: Reducer;
  };
}

const Model: ModelType = {
  namespace: 'preReChargeAudit',

  state: {
    auditList: [],
    partnerGarden: {
      count: 0,
      list: [],
    },
  },

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryList, payload);
      yield put({
        type: 'save',
        payload: response.body || [],
      });
    },

    * fetchPartner({ payload }, { call, put }) {
      const response = yield call(queryPartner, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'savePartner',
        payload: response.body,
      });
    },

    * allow({ payload }, { call, put }) {
      const response = yield call(allowAudit, payload.params);
      if (response.code === 0) {
        message.success('通过成功');
        yield put({
          type: 'fetch',
          payload: payload.search,
        });
      }

      return response;
    },

    * refuse({ payload }, { call, put }) {
      const response = yield call(refuseAudit, payload.params);
      const data = fetchValidation(response);
      if (data) {
        message.success('驳回成功');
        yield put({
          type: 'fetch',
          payload: payload.search,
        });
      }
    },

    * relieve({ payload }, { call, put }) {
      const response = yield call(relieveAudit, payload.params);
      const data = fetchValidation(response);
      if (data) {
        message.success('解除成功');
        yield put({
          type: 'fetch',
          payload: payload.search,
        });
      }
    },

    * arrears({ payload }, { call, put }) {
      const response = yield call(arrearsAvailable, payload.params);
      const data = fetchValidation(response);
      if (data) {
        message.success('修改成功');
        yield put({
          type: 'fetch',
          payload: payload.search,
        });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        auditList: action.payload,
      };
    },

    savePartner(state, action) {
      return {
        ...state,
        partnerGarden: action.payload,
      };
    },
  },
};

export default Model;
